import 'dart:developer';

import 'package:edu/constants/app_regex.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class ForgotPasswordSettingPageLogic extends ChangeNotifier {
  late final textController = TextEditingController();
  late final focusNode = FocusNode();

  late final _emailRegex = RegExp(AppRegex.email);
  late final _phoneRegex = RegExp(AppRegex.phone);

  bool get canSubmit {
    final account = textController.text;
    return _emailRegex.hasMatch(account) || _phoneRegex.hasMatch(account);
  }

  final String prevRoute;
  ForgotPasswordSettingPageLogic({required this.prevRoute});

  void init() {
    textController.addListener(() {
      notifyListeners();
    });
  }

  Future<bool> submit() async {
    final account = textController.text;
    final String type;

    if (_emailRegex.hasMatch(account)) {
      type = 'email';
    } else if (_phoneRegex.hasMatch(account)) {
      type = 'phone';
    } else {
      return false;
    }
    focusNode.unfocus();

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.changeUserPassword(
        type,
        account,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.status != null) {
        final tipMessage = type == 'email'
            ? AppStrings.emailVerifyCodeSended
            : AppStrings.phoneNumberVerifyCodeSended;
        EasyLoading.showSuccess(tipMessage);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }
}
